<template>
  <div class="my-address">
    <ZJHeader title="收货地址" class="address-header">
      <template #left>
        <van-icon name="arrow-left" @click="handleHeaderLeftClick"/>
      </template>
      <template #right>
        <p @click="handleToggleMode">{{ isManageMode ? "完成" : "管理" }}</p>
      </template>
    </ZJHeader>
    <div class="address-wrapper">
      <ZJScrollView
          wrapperInfo=".address-wrapper .scroll-wrapper"
          ref="scrollViewRef"
          :wrapperConfig="scrollWrapperConfig"
      >
        <template #content>
          <template v-if="addressList.length">
            <div class="wrapper-list">
              <div @click="handlePaymentItemClick(item.id)" v-for="item in addressList" :key="item.id"
                   :class="itemClassName">
                <!--       信息部分       -->
                <div class="item-common">
                  <div class="common-left">
                    <span class="left-circle">{{ item.receiverName.substring(0, 1) }}</span>
                  </div>
                  <div class="common-main">
                    <div class="main-word">
                      <span class="word-username">{{ item.receiverName }}</span>
                      <span class="word-phone">{{ item.receiverMobile }}</span>
                      <template v-if="item.receiverDefault">
                        <span class="word-default">默认</span>
                      </template>
                    </div>
                    <div class="main-sentence">
                      {{ item.wholeAddress }}
                    </div>
                  </div>
                  <div class="common-right">
                    <van-icon @click.stop="handleOpenForm('edit', item.id)" class="right-icon" name="edit"/>
                  </div>
                </div>
                <!--       点击管理后的部分       -->
                <div class="item-manage" v-show="isManageMode">
                  <div class="manage-left">
                    <van-button
                        round
                        icon="checked"
                        :class="item.receiverDefault ? 'checked-icon' : 'check-icon'"
                        @touchstart.stop="handleUpdateDefault(item.id)"
                    />
                    <span>默认地址</span>
                  </div>
                  <div class="manage-right" @click.stop="handleDeleteAddress(item.id)">删除</div>
                </div>
              </div>
            </div>
          </template>
          <template v-else>
            <van-empty description="快去添加一个地址吧~"/>
          </template>
        </template>
      </ZJScrollView>
    </div>
    <div class="address-add">
      <van-button @click="handleOpenForm('add')" round block type="primary">
        添加收货地址
      </van-button>
    </div>
    <router-view v-slot="{Component}">
      <keep-alive>
        <component :is="Component"></component>
      </keep-alive>
    </router-view>
  </div>
</template>

<script setup lang="ts">
import {computed, nextTick, onActivated, onBeforeUnmount, onMounted, ref, watch} from "vue";
import {useRoute, useRouter} from "vue-router";

import areaList from "@/constants/area"
import useMyModule from "@/store/myModule";
import {IAddress} from "@/store/myModule/types";
import ZJHeader from "../../../components/ZJHeader/ZJHeader.vue";
import {IAddressDetail} from "@/views/ZJMy/MyAddress/AddressForm/types";
import ZJScrollView from "../../../components/ZJScrollView/ZJScrollView.vue";
import {Dialog, Toast} from "vant";
import usePayModule from "@/store/payModule";
import useShopCarModule from "@/store/shopCarModule";
// 初始化变量
const route = useRoute()
const myModule = useMyModule()
const shopCarModule = useShopCarModule()
// 配置scrollView
const scrollViewRef = ref<InstanceType<typeof ZJScrollView>>(null)
const scrollWrapperConfig = {
  bounce: false,
  click: true
}

const {isFromShopCar} = defineProps({
  isFromShopCar: {
    type: Boolean,
    default: false
  }
})

// 模式切换相关
const isManageMode = ref(false)
const itemClassName = computed(() => ({
  "list-item": true,
  "manage": isManageMode.value
}))
const handleToggleMode = () => {
  isManageMode.value = !isManageMode.value
  setTimeout(() => {
    scrollViewRef.value.bs.refresh()
  })
}

// 初始化地址列表
const addressList = ref<Array<IAddressDetail>>([])
const setupAddressList = async () => {
  const data = await myModule.getMyAddressAction({
    needNavigate: "/my/address"
  })
  if (data) {
    addressList.value = data as Array<IAddress>
    addressList.value = addressList.value.map(item => {
      const provinceCode = item.receiverProvince ?? ""
      const cityCode = item.receiverCity ?? ""
      const districtCode = item.receiverDistrict ?? ""
      const {province_list, city_list, county_list} = areaList
      item.wholeAddress = `${province_list[provinceCode]} ${city_list[cityCode]} ${county_list[districtCode]} ${item.receiverAddress}`
      return item
    })
  }
}
// 修改默认地址
const handleUpdateDefault = async (addressId: number) => {
  const isSuccess = await myModule.editDefaultAddressAction({
    addressId
  })
  if (isSuccess) {
    Toast.success("已修改默认地址")
    await setupAddressList()
  }
}
// 删除地址
const handleDeleteAddress = async (addressId: number) => {
  Dialog.confirm({
    title: '提示',
    message:
        '确定要删除这个地址吗？',
  })
      .then(async () => {
        const isSuccess = await myModule.deleteAddressAction({
          addressId
        })
        if (isSuccess) {
          Toast.success("删除成功")
          await setupAddressList()
          // 如果是提交订单页过来的
          if (isPayment.value) {
            const chosenId = payModule.currentChooseAddress.id
            chosenId === addressId && payModule.resetChooseAddressAction()
          }
        }
      })
      .catch(() => {
      });
}
// 打开增加修改表单
const router = useRouter()
const handleOpenForm = (type: string, id?: number) => {
  let query = {
    type,
    id
  }
  router.push({
    name: "MyAddressManage",
    query
  })
}
// 每次进入页面都重新刷新一下
onMounted(async () => {
  await setupAddressList()
  await nextTick(() => {
    scrollViewRef.value.bs.refresh()
  })
})
const stopWatch = watch(route, async () => {
  if (route.path === "/my/address") {
    await setupAddressList()
  }
})
onBeforeUnmount(() => {
  stopWatch()
})
const handleHeaderLeftClick = () => {
  if (isFromShopCar) {
    shopCarModule.setIsShowAddressAction(false)
  } else {
    router.back()
  }
}
// 支付页面调过来的话
const isPayment = ref(false)
const payModule = usePayModule()
const handlePaymentItemClick = async (addressId: number) => {
  if (isPayment.value) { // 如果是支付跳转来的
    const chooseAddress = await myModule.getMyAddressAction({
      id: addressId,
      needNavigate: "/my/address"
    })
    if (chooseAddress) {
      payModule.setChooseAddressAction(chooseAddress as IAddress)
      router.back()
    }
  } else if (isFromShopCar) { // 如果是购物车跳转来的
    const chooseAddress = await myModule.getMyAddressAction({
      id: addressId,
      needNavigate: "/my/address"
    })
    shopCarModule.setCurrentAddressAction(chooseAddress as IAddress)
    shopCarModule.setIsShowAddressAction(false)
  }
}
onActivated(() => {
  const operateType = route.query.type ?? ""
  console.log(operateType)
  if (operateType === "payment") {
    isPayment.value = true
  }
})
</script>

<style scoped lang="less">
@import "src/assets/css/variable";
@import "src/assets/css/mixins";

.my-address {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  z-index: 888;
  background-color: @theme-grey-color;

  .address-wrapper {
    height: calc(100% - 50px - 60px);
    box-sizing: border-box;
    overflow: hidden;

    .wrapper-list {
      width: 95%;
      margin: 10px auto;
      border-radius: 10px;
      overflow: hidden;

      .list-item {
        padding: 10px;
        background-color: #fff;
        margin-bottom: 10px;

        &:last-of-type {
          margin-bottom: 0;
        }

        .item-common {
          display: flex;
          align-items: center;

          .common-left {
            .left-circle {
              display: block;
              text-align: center;
              line-height: 30px;
              width: 30px;
              height: 30px;
              background-color: @theme-color;
              border-radius: 50%;
              color: #fff;
            }

            margin-right: 10px;
          }

          .common-main {
            flex: 1;

            .main-word {
              margin-bottom: 4px;

              .word-username {
                font-size: 18px;
                font-weight: 600;
              }

              .word-phone {
                color: #999;
              }

              .word-default {
                color: @theme-color;
                border: 1px solid @theme-color;
                border-radius: 4px;
                padding: 2px;
                font-size: 14px;
                text-align: center;
              }

              span {
                margin-right: 4px;
              }
            }

            .main-sentence {
              overflow: hidden; //溢出内容隐藏
              text-overflow: ellipsis; //文本溢出部分用省略号表示
              display: -webkit-box; //特别显示模式
              -webkit-line-clamp: 2; //行数
              line-clamp: 2;
              -webkit-box-orient: vertical; //盒子中内容竖直排列
            }
          }

          .common-right {
            margin-left: 10px;

            .right-icon {
              font-size: 20px;
            }
          }
        }

        .item-manage {
          margin-top: 8px;
          padding-top: 8px;
          border-top: 1px solid #f2f2f2;
          display: flex;
          justify-content: space-between;

          .manage-left {
            display: flex;
            align-items: center;

            .checked-icon {
              width: 30px;
              height: 30px;
              color: @theme-color;
              padding: 0 !important;
            }

            .check-icon {
              width: 30px;
              height: 30px;
              color: #ccc;
              padding: 0 !important;
            }
          }
        }

        &.manage {
          border-radius: 10px;
          margin-top: 10px;

          &:first-of-type {
            margin-top: 0;
          }
        }
      }
    }
  }

  .address-add {
    position: fixed;
    bottom: 0;
    height: 60px;
    width: 100%;
    background-color: #fff;
    padding: 0 20px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
  }
}
</style>
